﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Text;

namespace SCM.Common.SMS
{

    public interface IAliSMS
    {
        string SendSMS(string phone, string signName, string tempCode, string tempPram);
    }

    public class AliSMSHelper: IAliSMS
    {
        private string accessKeyId, accessSecret;
        IClientProfile profile = null;
        public AliSMSHelper(string ak, string sk)
        {
            accessKeyId = ak;
            accessSecret = sk;
            profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessSecret);
        }

        public string SendSMS(string phone, string signName, string tempCode, string tempPram)
        {
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendSms";
            request.AddQueryParameters("PhoneNumbers", phone);
            request.AddQueryParameters("SignName", signName);
            request.AddQueryParameters("TemplateCode", tempCode);
            request.AddQueryParameters("TemplateParam", tempPram);
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                string data = Encoding.Default.GetString(response.HttpResponse.Content);
                Dictionary<string, string> keys = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
                string code = "";
                if (keys.TryGetValue("Code", out code))
                {
                    if (code == "OK")
                    {
                        return "";
                    }
                }
                if (keys.TryGetValue("Message", out code))
                {
                    return code;
                }
                return "短信发送失败";
            }
            catch (ServerException e)
            {
                return e.Message;
            }
            catch (ClientException e)
            {
                return e.Message;
            }
        }
    }
}
